<template>
  <div>
    <el-dialog
      title="新建歌单"
      :visible.sync="dialogVisible"
      :width="dialogWidth"
      center
      top="35vh"
      :close-on-click-modal="false"
    >
      <el-form :model="form">
        <el-form-item>
          <el-input
            v-model="form.title"
            autocomplete="off"
            placeholder="请输入新建歌单的标题"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-switch
            v-model="form.isPublic"
            active-text="公开歌单"
            inactive-text="私有歌单">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="small"
          round
          @click="handleCreatePlayList"
          class="btn-create"
          :disabled="disabledCreate"
          >创建</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import { isEmpty } from "lodash-es";
import { postCreatePlayList } from "@/api/api_playlist";
export default {
  data() {
    return {
      dialogVisible: false,
      formLabelWidth: "7.5rem",
      form: {
        title: "",
        isPublic:false,//是否公开歌单
      },
      disabledCreate: true,
    };
  },
  computed: {
    ...mapState(["isPhone"]),
    ...mapGetters(["createPlaylist"]),
    dialogWidth() {
      return this.isPhone ? "80%" : "37.5rem";
    },
  },
  watch: {
    "form.title"(newVal) {
      if (!isEmpty(newVal.trim())) {
        this.disabledCreate = false;
      } else {
        this.disabledCreate = true;
      }
    },
    dialogVisible() {
      this.form.title = "";
    },
  },
  methods: {
    openDialog() {
      this.dialogVisible = true;
    },
    async handleCreatePlayList() {
      try {
        const { title } = this.form;
        const isPublic=this.form.isPublic?1:0;
        const res = await postCreatePlayList(title,isPublic);
        console.log(res,"==============");
        if (res.status !== 200) {
          this.$message.error("创建失败");
        }
        this.$message.success("创建成功");
        const {
          data: {
            data: { id },
          },
        } = res;
        this.$router.push({ path: `/playlistdetail/${id}` });
        this.dialogVisible = false;
        this.$store.dispatch("getMyPlayList");
      } catch (err) {
        this.$message.error(err);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.btn-create {
  width: 6.25rem;
}
</style>
